package com.hashimoto.core.handler.decodec;

import java.util.List;

import com.hashimoto.core.message.LoginResultSignal;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;

public class LoginResultSignalCodec implements Codec<LoginResultSignal> {
	
	
	//  code + msgLength 
    private static int mutableLength = 4 + 4;

	@Override
	public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out, int beginIndex) throws Exception {
		boolean isEnough =  lengthEnough(in, mutableLength, beginIndex);
		if(!isEnough)return ;
		int code = in.readInt();
		int msgLength = in.readInt();
		int size = in.readableBytes();
		if(size < msgLength) {
			in.readerIndex(beginIndex);
			return;
		}
		
		byte[] msgData = new byte[msgLength];
		in.readBytes(msgData);
		LoginResultSignal loginResult = new LoginResultSignal();
		loginResult.setCode(code);
		loginResult.setMessage(msgLength == 0 ? null : new String(msgData));
		out.add(loginResult);
	}

	@Override
	public void encode(ChannelHandlerContext ctx, LoginResultSignal msg, ByteBuf out) throws Exception {
		out.writeInt(msg.getCode());
		writeString(out,msg.getMessage());
	}

}
